<template>
  <div class="page">
    <div v-if="product" class="product-detail">
      <!-- 商品图片 -->
      <div class="product-images">
        <img 
          :src="product.mainImage || '/placeholder.svg'" 
          :alt="product.name"
          class="main-image"
          @error="handleImageError"
        />
      </div>

      <!-- 商品信息 -->
      <div class="product-info">
        <h1 class="product-name">{{ product.name }}</h1>
        <div class="product-price">
          <span class="current-price">¥{{ product.price }}</span>
          <span v-if="product.originalPrice" class="original-price">¥{{ product.originalPrice }}</span>
        </div>
        <div class="product-meta">
          <span class="stock">库存: {{ product.stock }}件</span>
          <span class="sales">已售: {{ product.soldCount || 0 }}件</span>
        </div>
      </div>

      <!-- 商品描述 -->
      <div class="product-description">
        <h3>商品描述</h3>
        <p>{{ product.description }}</p>
      </div>

      <!-- 购买按钮 -->
      <div class="purchase-actions">
        <el-button 
          type="primary" 
          size="large"
          :loading="addingToCart"
          @click="addToCart"
        >
          {{ addingToCart ? '添加中...' : '加入购物车' }}
        </el-button>
        <el-button type="default" size="large">立即购买</el-button>
      </div>

      <!-- 商品评价 -->
      <ReviewSection :product-id="parseInt(productId as string)" />

    </div>
    <div v-else class="error-message">
      <div class="error-icon">❌</div>
      <div class="error-text">商品不存在或加载失败</div>
      <el-button type="primary" @click="goBack">返回</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { getProductById } from '@/api/product'
import { useCartStore } from '@/stores/cart'
import { useUserStore } from '@/stores/user'
import ReviewSection from '@/components/ReviewSection.vue'
import { showFullscreenLoading } from '@/utils/loading'
import { ElMessage } from 'element-plus'

const router = useRouter()
const route = useRoute()
const productId = route.params.id

const cartStore = useCartStore()
const userStore = useUserStore()

const product = ref<any>(null)
const addingToCart = ref(false)

const loadProduct = async () => {
  if (!productId) return
  
  const loading = showFullscreenLoading({
    text: '正在加载商品信息...'
  })
  
  try {
    const response = await getProductById(parseInt(productId as string))
    if (response.data.success) {
      product.value = response.data.data
    }
  } catch (error) {
    console.error('加载商品失败:', error)
  } finally {
    loading.close()
  }
}

const addToCart = async () => {
  if (!userStore.user) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  
  try {
    addingToCart.value = true
    await cartStore.addToCart({
      productId: product.value.id,
      quantity: 1
    })
    ElMessage.success('已添加到购物车')
  } catch (error) {
    console.error('添加到购物车失败:', error)
    ElMessage.error('添加失败，请重试')
  } finally {
    addingToCart.value = false
  }
}

const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  img.src = '/placeholder.svg'
}

const goBack = () => {
  router.back()
}

onMounted(() => {
  loadProduct()
})
</script>

<style scoped>
.product-detail {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 20px;
}

.product-images {
  position: relative;
}

.main-image {
  width: 100%;
  height: 300px;
  position: relative;
}

.product-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
}

.image-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 18px;
  font-weight: bold;
  text-align: center;
  padding: 20px;
  border-radius: 8px;
}

.image-thumbnails {
  display: flex;
  gap: 10px;
  padding: 15px;
  overflow-x: auto;
}

.thumbnail {
  flex-shrink: 0;
  cursor: pointer;
  border: 2px solid transparent;
  border-radius: 8px;
  transition: border-color 0.3s ease;
}

.thumbnail.active {
  border-color: #007aff;
}

.thumbnail-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 6px;
}

.thumbnail-placeholder {
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 10px;
  text-align: center;
  border-radius: 6px;
}

.product-info {
  padding: 20px;
}

.product-name {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
}

.product-price {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;
}

.current-price {
  font-size: 28px;
  font-weight: bold;
  color: #ff3b30;
}

.original-price {
  font-size: 16px;
  color: #999;
  text-decoration: line-through;
}

.product-description {
  color: #666;
  line-height: 1.6;
  margin-bottom: 20px;
}

.product-attributes {
  margin-bottom: 30px;
}

.attribute {
  display: flex;
  justify-content: space-between;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.attribute:last-child {
  border-bottom: none;
}

.label {
  color: #666;
  font-weight: 500;
}

.value {
  color: #333;
}

.purchase-actions {
  border-top: 1px solid #f0f0f0;
  padding-top: 20px;
}

.quantity-selector {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 15px;
  margin-bottom: 20px;
}

.quantity-btn {
  width: 40px;
  height: 40px;
  border: 1px solid #ddd;
  background: #fff;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 18px;
}

.quantity {
  font-size: 18px;
  font-weight: bold;
  min-width: 40px;
  text-align: center;
}

.action-buttons {
  display: flex;
  gap: 15px;
}

.action-buttons .btn {
  flex: 1;
  padding: 15px;
  font-size: 16px;
}

.error-message {
  text-align: center;
  padding: 60px 20px;
}

.error-icon {
  font-size: 60px;
  margin-bottom: 20px;
}

.error-text {
  font-size: 18px;
  color: #666;
  margin-bottom: 30px;
}

.back-btn {
  background: none;
  border: none;
  color: #007aff;
  font-size: 16px;
  cursor: pointer;
  padding: 10px 0;
  margin-bottom: 10px;
}
</style> 